import {
  init,
  Geolocation,
  setNeedAddress,
  setLocatingWithReGeocode,
  Position,
  setDistanceFilter,
  setInterval,
  start,
} from 'react-native-amap-geolocation';
import {PermissionsAndroid, Platform} from 'react-native';
import {useLocationStore} from '@/store/locationStore/locationStore';
import {useCallback, useEffect, useMemo, useState} from 'react';
// export type Position = {
//   latitude: string | number;
//   longitude: string | number;
// };
/**
 * 获取经纬度坐标
 * latitude 经度
 * longitude 纬度
 */
export const requestLocationPermission = async (): Promise<Position> => {
  return new Promise(async (resolve, reject) => {
    // 对于 Android 需要自行根据需要申请权限
    if (Platform.OS === 'android') {
      await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
      ]);
      setNeedAddress(true);
      // android，5 秒请求一次定位
      setInterval(5000);
    } else {
      // ios
      setLocatingWithReGeocode(true);
      // ios，设备移动超过 10 米才会更新位置信息
      setDistanceFilter(10);
    }

    // 使用自己申请的高德 App Key 进行初始化
    await init({
      ios: '6f38b617d3e5b518c907b34526d224fe',
      android: '1d94df2b090ca5c811054426134b3c88',
    });

    Geolocation.getCurrentPosition(
      result => {
        resolve(result);
      },
      err => {
        reject(err);
      },
    );
    start();
  });
};

export const useReqCoordinate = () => {
  const {setAddressName, setCoordinate, setRegionName} = useLocationStore();
  const [hasExecute, setHasExecute] = useState(false);
  const fnOne = useCallback(async () => {
    const locationPos: Position = await requestLocationPermission();
    // console.log(locationPos);
    setCoordinate({
      altitude: locationPos.coords.latitude,
      longitude: locationPos.coords.longitude,
    });
    const location = locationPos.location;
    setRegionName(location.city);
    setAddressName(location.poiName);
  }, [setAddressName, setCoordinate]);
  useEffect(() => {
    console.log('requestLocation');
    fnOne();
    setHasExecute(true);
  }, [setAddressName, setCoordinate, fnOne, hasExecute]);
  // return [hasExecute, setHasExecute];
};
